package org.my.stock.h2.util;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.brotli.dec.BrotliInputStream;

import java.io.IOException;
import java.io.InputStream;

public class BrotliHttpClientHelper {
    // 创建支持 Brotli 的 HttpClient
    public static HttpClient createBrotliClient() {
        return HttpClients.custom()
                .addInterceptorFirst((HttpResponse response, HttpContext context) -> {
                    // 替换默认解压逻辑
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String contentEncoding = entity.getContentEncoding() != null
                                ? entity.getContentEncoding().getValue()
                                : "";
                        if (contentEncoding.contains("br")) {
                            response.setEntity(new BrotliDecompressingEntity(entity));
                        }
                    }
                })
                .build();
    }

    // Brotli 解压实体类
    private static class BrotliDecompressingEntity extends org.apache.http.entity.HttpEntityWrapper {
        public BrotliDecompressingEntity(HttpEntity entity) {
            super(entity);
        }

        @Override
        public InputStream getContent() throws IOException {
            return new BrotliInputStream(wrappedEntity.getContent());
        }

        @Override
        public long getContentLength() {
            return -1; // 解压后长度未知
        }
    }
}
